import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/page/person/model/pay_order_entity.dart';
import 'package:tobias/tobias.dart' as tobias;

typedef PaymmentCallBack = Function(bool isSuccess, int errCode, String msg);

class PayUtils {
  /// 支付
  /// paychannel 支付渠道 （参见AppConstant）
  /// callBack 支付完成的回调
  static Future<bool> startPay(
      int payChannel, PayOrderEntity entity, PaymmentCallBack callBack) async {
    if (payChannel == AppConstant.PAY_CHANNEL_WX) {
      /// 微信支付
      fluwx.weChatResponseEventHandler.listen((payResult) {
        if (payResult is fluwx.WeChatPaymentResponse) {
          print("支付结果");
          print(payResult.errStr);
          print(payResult.errCode);
          String msg = payResult.isSuccessful ? "支付成功" : payResult.errStr;
          callBack(payResult.isSuccessful, payResult.errCode, msg);
        }
      });
      bool res = await fluwx.payWithWeChat(
        appId: entity.appid,
        partnerId: entity.partnerid,
        prepayId: entity.prepayid,
        packageValue: entity.package,
        nonceStr: entity.noncestr,
        timeStamp: int.parse(entity.timestamp),
        sign: entity.sign,
      );
      return res;
    } else if (payChannel == AppConstant.PAY_CHANNEL_ALi) {
      /// 支付宝支付
      var payResult = await tobias.aliPay(entity.info);
      print(payResult);
      String code = payResult["resultStatus"];
      String msg = code == "9000" ? "支付成功" : payResult["memo"];
      bool isSuccessful = code == "9000" ? true : false;
      callBack(isSuccessful, int.parse(code), msg);
      return true;
    } else {
      return false;
    }
  }
}
